use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::products::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub brand_id: String,
    pub product_image_id: String,
    pub product_video_id: String,
    pub product_sku_id: String,
    pub tax_class_id: String,
    pub slug: Option<String>,
    pub variables: Option<serde_json::Value>,
    pub is_virtual: i8,
    pub position: i32,
    pub weight: rust_decimal::Decimal,
    pub weight_class: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Brand ID must not be empty."))]
    pub brand_id: String,
    #[validate(length(min = 1, message = "Product SKU ID must not be empty."))]
    pub product_sku_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            brand_id: self.brand_id.as_ref().to_owned(),
            product_sku_id: self.product_sku_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::products::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a product by the provided id
    ///
    /// # Errors
    ///
    /// When could not find product or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let product = products::Entity::find()
            .filter(
                model::query::condition()
                    .eq(products::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        product.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds a product by the provided slug
    ///
    /// # Errors
    ///
    /// When could not find product or DB query error
    pub async fn find_by_slug(db: &DatabaseConnection, slug: &str) -> ModelResult<Self> {
        let product = products::Entity::find()
            .filter(
                model::query::condition()
                    .eq(products::Column::Slug, slug)
                    .build(),
            )
            .one(db)
            .await?;
        product.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// Asynchronously creates a product and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the product into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        if let Some(slug) = &params.slug {
            if products::Entity::find()
                .filter(
                    model::query::condition()
                        .eq(products::Column::Slug, slug)
                        .build(),
                )
                .one(&txn)
                .await?
                .is_some()
            {
                return Err(ModelError::EntityAlreadyExists {});
            }
        }

        let product = products::ActiveModel {
            brand_id: ActiveValue::set(params.brand_id.to_string()),
            product_image_id: ActiveValue::set(params.product_image_id.to_string()),
            product_video_id: ActiveValue::set(params.product_video_id.to_string()),
            product_sku_id: ActiveValue::set(params.product_sku_id.to_string()),
            tax_class_id: ActiveValue::set(params.tax_class_id.to_string()),
            slug: ActiveValue::set(params.slug.clone()),
            variables: ActiveValue::set(params.variables.clone()),
            is_virtual: ActiveValue::set(params.is_virtual),
            position: ActiveValue::set(params.position),
            weight: ActiveValue::set(params.weight.into()),
            weight_class: ActiveValue::set(params.weight_class.to_string()),
            active: ActiveValue::set(1),
            sales: ActiveValue::set(0),
            viewed: ActiveValue::set(0),
            published_at: ActiveValue::set(Some(chrono::Utc::now().into())),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(product)
    }
}

impl ActiveModel {
    /// Updates the product's active status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_active_status(
        mut self,
        db: &DatabaseConnection,
        active: bool,
    ) -> ModelResult<Model> {
        self.active = ActiveValue::set(if active { 1 } else { 0 });
        Ok(self.update(db).await?)
    }

    /// Updates the product's position
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_position(
        mut self,
        db: &DatabaseConnection,
        position: i32,
    ) -> ModelResult<Model> {
        self.position = ActiveValue::set(position);
        Ok(self.update(db).await?)
    }
}
